//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.mass.core.activiti.workflow.service;

import com.mass.core.utils.WorkflowUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.delegate.ActivityBehavior;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WorkflowTraceService {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    protected RuntimeService runtimeService;
    @Autowired
    protected TaskService taskService;
    @Autowired
    protected RepositoryService repositoryService;
    @Autowired
    protected IdentityService identityService;

    public WorkflowTraceService() {
    }

    @SuppressWarnings("unchecked")
	public List<Map<String, Object>> traceProcess(String processInstanceId) throws Exception {
        Execution execution = (Execution)this.runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult();
        Object property = PropertyUtils.getProperty(execution, "activityId");
        String activityId = "";
        if(property != null) {
            activityId = property.toString();
        }

        ProcessInstance processInstance = (ProcessInstance)this.runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity)((RepositoryServiceImpl)this.repositoryService).getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
		List<?> activitiList = processDefinition.getActivities();
		ArrayList<Map<String, Object>> activityInfos = new ArrayList<Map<String, Object>>();
		Iterator<?> var10 = activitiList.iterator();

        while(var10.hasNext()) {
            ActivityImpl activity = (ActivityImpl)var10.next();
            boolean currentActiviti = false;
            String id = activity.getId();
            if(id.equals(activityId)) {
                currentActiviti = true;
            }

            @SuppressWarnings("rawtypes")
			Map activityImageInfo = this.packageSingleActivitiInfo(activity, processInstance, currentActiviti);
            activityInfos.add(activityImageInfo);
        }

        return activityInfos;
    }

	private Map<String, Object> packageSingleActivitiInfo(ActivityImpl activity, ProcessInstance processInstance, boolean currentActiviti) throws Exception {
        HashMap<String, Object> vars = new HashMap<String, Object>();
        HashMap<String, Object> activityInfo = new HashMap<String, Object>();
        activityInfo.put("currentActiviti", Boolean.valueOf(currentActiviti));
        this.setPosition(activity, activityInfo);
        this.setWidthAndHeight(activity, activityInfo);
        Map<?, ?> properties = activity.getProperties();
        vars.put("任务类型", WorkflowUtils.parseToZhType(properties.get("type").toString()));
        ActivityBehavior activityBehavior = activity.getActivityBehavior();
        this.logger.debug("activityBehavior={}", activityBehavior);
        if(activityBehavior instanceof UserTaskActivityBehavior) {
            Task description = null;
            if(currentActiviti) {
                description = this.getCurrentTaskInfo(processInstance);
            }

            UserTaskActivityBehavior userTaskActivityBehavior = (UserTaskActivityBehavior)activityBehavior;
            TaskDefinition taskDefinition = userTaskActivityBehavior.getTaskDefinition();
            Set<Expression> candidateGroupIdExpressions = taskDefinition.getCandidateGroupIdExpressions();
            if(!candidateGroupIdExpressions.isEmpty()) {
                this.setTaskGroup(vars, candidateGroupIdExpressions);
                if(description != null) {
                    this.setCurrentTaskAssignee(vars, description);
                }
            }
        }

        vars.put("节点说明", properties.get("documentation"));
        String description1 = activity.getProcessDefinition().getDescription();
        vars.put("描述", description1);
        this.logger.debug("trace variables: {}", vars);
        activityInfo.put("vars", vars);
        return activityInfo;
    }

    private void setTaskGroup(Map<String, Object> vars, Set<Expression> candidateGroupIdExpressions) {
        String roles = "";

        String roleName;
        for(Iterator<Expression> var5 = candidateGroupIdExpressions.iterator(); var5.hasNext(); roles = roles + roleName) {
            Expression expression = (Expression)var5.next();
            String expressionText = expression.getExpressionText();
            roleName = ((Group)this.identityService.createGroupQuery().groupId(expressionText).singleResult()).getName();
        }

        vars.put("任务所属角色", roles);
    }

    private void setCurrentTaskAssignee(Map<String, Object> vars, Task currentTask) {
        String assignee = currentTask.getAssignee();
        if(assignee != null) {
            User assigneeUser = (User)this.identityService.createUserQuery().userId(assignee).singleResult();
            String userInfo = assigneeUser.getFirstName() + " " + assigneeUser.getLastName();
            vars.put("当前处理人", userInfo);
        }

    }

    private Task getCurrentTaskInfo(ProcessInstance processInstance) {
        Task currentTask = null;

        try {
            String e = (String)PropertyUtils.getProperty(processInstance, "activityId");
            this.logger.debug("current activity id: {}", e);
            currentTask = (Task)((TaskQuery)((TaskQuery)this.taskService.createTaskQuery().processInstanceId(processInstance.getId())).taskDefinitionKey(e)).singleResult();
            this.logger.debug("current task for processInstance: {}", ToStringBuilder.reflectionToString(currentTask));
        } catch (Exception var4) {
            this.logger.error("can not get property activityId from processInstance: {}", processInstance);
        }

        return currentTask;
    }

    private void setWidthAndHeight(ActivityImpl activity, Map<String, Object> activityInfo) {
        activityInfo.put("width", Integer.valueOf(activity.getWidth()));
        activityInfo.put("height", Integer.valueOf(activity.getHeight()));
    }

    private void setPosition(ActivityImpl activity, Map<String, Object> activityInfo) {
        activityInfo.put("x", Integer.valueOf(activity.getX()));
        activityInfo.put("y", Integer.valueOf(activity.getY()));
    }
}
